home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12944 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Recursion
  5. Date: Wed, 03 Apr 96 16:17:45 GMT
  6. Organization: none
  7. Message-ID: <828548265snz@genesis.demon.co.uk>
  8. References: <31624BC2.70D2@sooner.net>
  9. Reply-To: fred@genesis.demon.co.uk
  10. X-NNTP-Posting-Host: genesis.demon.co.uk
  11. X-Newsreader: Demon Internet Simple News v1.27
  12. X-Mail2News-Path: genesis.demon.co.uk
  13.  
  14. In article <31624BC2.70D2@sooner.net> edwbush@sooner.net "Eddie Bush" writes:
  15.  
  16. >I am trying to construct a C function that will recursively convert
  17. >a string such as "1234" into it's integer equivelant (1234).
  18. >
  19. >Here is what I know:
  20. >1)if you subtract the character "0" from any of the other digits "1".."9"
  21. >  you will get the integer value of that characer.
  22. >        Example:  "1" - "0" is equal to 1
  23.  
  24. Not true "1" and "0" are strings (i.e. have type array of char) and -
  25. cannot be applied to 2 of these. However '1' - '0' is equal to 1.
  26.  
  27.  
  28. >                  "2" - "0" is equal to 2
  29. >                  .
  30. >                  .
  31. >                  .
  32. >                  "9" - "0" is equal to 9
  33.  
  34. Similarly.
  35.  
  36. >2)the function should be called with a character pointer:
  37. >        Such as:   convert("1234");
  38. >  making the prototype look something like:
  39. >        int convert(char *p);
  40.  
  41. Or consider
  42.  
  43.          int convert(const char *p);
  44.  
  45. since you aren't going to modify the source string (certainly not if it
  46. could be a string literal).
  47.  
  48. >Does anyone have an idea?  This is sorta stumping me.  I am aware of 
  49. >atoi, but I am wanting to write a recursive function that does that -- 
  50. >for the fun of it.  It's sort of a little puzzle to help me learn 
  51. >recursion.  Any ideas?
  52.  
  53. I think you've picked a bad example. You really need an extra argument in
  54. this case to pass on a running accumulator. A more suitable problem would
  55. be to write a recursive function that is passed an integer (unsigned is
  56. easiest) and writes the character representation to stdout.
  57.  
  58. Define a recursive algorithm i.e. one defined in terms of a simpler form
  59. of the problem, with a termination condition (i.e. hitting the end of the
  60. input string in this case). Consider
  61.  
  62. -- 
  63. -----------------------------------------
  64. Lawrence Kirby | fred@genesis.demon.co.uk
  65. Wilts, England | 70734.126@compuserve.com
  66. -----------------------------------------
  67.